package de.dhbw.karlsruhe.picsim.gui.control;

import de.dhbw.karlsruhe.picsim.rs232.ComManager;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: May 2, 2010
 * Time: 4:49:04 PM
 */
public final class ComSettings extends AbstractAction {
    private final JFrame parent;
    private final ComManager comManager;

    public ComSettings(final JFrame parent, final ComManager comManager) {
        super("COM");
        this.parent = parent;
        this.comManager = comManager;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        final JDialog dialog = new JDialog(parent);
        final JPanel contentPane = new JPanel();
        dialog.setContentPane(contentPane);
        final JLabel jLabel = new JLabel("Wählen sie einen Port");
        contentPane.add(jLabel);
        @SuppressWarnings({"UseOfObsoleteCollectionType"})
        final Vector<String> ports = new Vector<String>(comManager.getAllAvailablePorts());
        final JList jList = new JList(ports);
        if (ports.contains(comManager.getCurrentPort())) {
            jList.setSelectedIndex(ports.indexOf(comManager.getCurrentPort()));
        }
        contentPane.add(jList);
        contentPane.add(new JButton(new AbstractAction("OK") {
            @Override
            public void actionPerformed(ActionEvent e) {
                final int index = jList.getSelectedIndex();
                if (index == -1) {
                    comManager.closeActivePort();
                    dialog.setVisible(false);
                    dialog.dispose();
                } else if (comManager.changeComPort(ports.get(index))) {
                    dialog.setVisible(false);
                    dialog.dispose();
                } else {
                    jLabel.setText("Port konnte nicht geöffnet werden");
                }
            }

        }));
        dialog.setVisible(true);
        dialog.pack();

    }

    public void dispose() {
        comManager.dispose();
    }
}
